<template>
  <div v-loading="loading" :style="{ height: `calc(100vh - ${initTagViewHeight}` }" class="diagram-container">
    <!-- <el-input v-model="userId" placeholder="请输入用户ID" clearable @keyup.enter="initEchartsTree" /> -->
    <div ref="echartsTreeRef" style="height: 100%"></div>
    <div class="back-home">
      <el-input v-model="userId" placeholder="请输入用户ID" clearable @keyup.enter="handleQuery" />
    </div>

    <el-dialog v-model="twiceAuthCodeDialogVisible" :width="500" title="二次认证">
      <div class="auth-area1">
        <div class="auth-tips1">输入登录密码</div>
        <div class="auth-input">
          <el-input
            v-model="twiceAuthCode"
            auto-complete="off"
            placeholder="请输入输入登录密码"
            size="large"
            style="width: 100%"
            type="password"
          ></el-input>
        </div>
        <div class="auth-botton">
          <el-button size="large" style="width: 100%" type="primary" @click="twiceAuthSubmit">验证</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { toRefs, reactive, computed, onMounted, getCurrentInstance } from 'vue';
import { useRoute } from 'vue-router';
import * as echarts from 'echarts';
import { queryNetBody } from '@/api/business/diagram/index.js';
import { updateUser, openSafe } from '@/api/business/user';

export default {
  name: 'FunEchartsTree',
  setup() {
    const { proxy } = getCurrentInstance() as any;
    const state = reactive({
      tagViewHeight: '',
      keyword: '',
      selectId: '',
      loading: false,
      reUserList: [],
      allianceList: [],
      userId: null,
      twiceAuthCodeDialogVisible: false,
      twiceAuthCode: null
    });
    // 设置主内容的高度
    const initTagViewHeight = computed(() => {
      return `80px`;
    });
    // 组合数据
    const filterInfoData = (data) => {
      const children = [];
      if (data.left) children.push(filterInfoData(data.left));
      if (data.right) children.push(filterInfoData(data.right));
      return {
        ...data,
        children
      };
    };
    const changeId = () => {
      initEchartsTree(state.selectId ? state.selectId : state.userId);
    };

    // 初始化数据
    const initEchartsTree = (id?: number) => {
      console.log(id);
      state.loading = true;
      return new Promise((resolve) => {
        queryNetBody({
          userId: id
        }).then((res) => {
          console.log(res);
          const myChart = echarts.init(proxy.$refs.echartsTreeRef);
          const option = {
            tooltip: {
              trigger: 'item',
              triggerOn: 'mousemove'
            },
            series: [
              {
                type: 'tree',
                data: res.data,
                left: '2%',
                right: '2%',
                top: '10%',
                // bottom: '20%',
                orient: 'vertical',
                label: {
                  // position: 'center',
                  verticalAlign: 'middle',
                  align: 'center',
                  fontSize: 12,
                  formatter: (item) => {
                    // 网体关系增加用户详细，\n角色：${item.data.userType}\n上传商品数量：${item.data.uploadShopNum}\n${state.assetTypeName[1]}：${item.data.hdPoint}\n直接推荐人数：${item.data.directPersonNum}\n伞下推荐人数：${item.data.referees}}
                    //根据以上注释重新以下代码
                    return [
                      `{first|${item.data.id}}`,
                      `{second|地址：${item.data.label}\n序号：${item.data.mark}\n等级：${item.data.userLevel}\n算力：${item.data.computility}\n直推业绩：${item.data.directPushAchievement}\n团队业绩：${item.data.teamAchievement}\n个人业绩：${item.data.selfAchievement}\n今日新增业绩：${item.data.todayAddAchievement}\n伞下数量：${item.data.umbrellaNum}}\n`
                    ].join('\n');
                  },
                  rich: {
                    first: {
                      backgroundColor: '#409eff',
                      color: '#ffffff',
                      align: 'center',
                      width: 150,
                      height: 30,
                      borderRadius: [5, 5, 0, 0]
                    },
                    second: {
                      color: '#666666',
                      align: 'left',
                      lineHeight: 20,
                      width: 150,
                      height: 30,
                      borderRadius: [0, 0, 5, 5],
                      backgroundColor: '#f8f8f8'
                    }
                  }
                },
                leaves: {
                  label: {
                    verticalAlign: 'middle',
                    align: 'center'
                  }
                },
                emphasis: {
                  focus: 'descendant'
                },
                progressiveRendering: true,
                animationDuration: 550,
                animationDurationUpdate: 750,
                symbolSize: [100, 85],
                itemStyle: {
                  color: 'transparent',
                  borderWidth: 0
                },
                lineStyle: {
                  color: '#D5D5D5',
                  width: 1,
                  curveness: 0.5
                },
                tooltip: {
                  show: false,
                  formatter: (item) => {
                    return JSON.stringify(item.data);
                  }
                },

                roam: true,
                draggable: true // 节点可拖动
              }
            ]
          };
          myChart.setOption(option);

          // myChart.on('finished', function() {
          //     var series = myChart.getModel().getSeriesByIndex(0);
          //     var data = series.getData();

          //     data.each(function(idx) {
          //         var itemLayout = data.getItemLayout(idx);
          //         if (itemLayout) {
          //             myChart.getZr().add(new echarts.graphic.Text({
          //                 x: itemLayout[0] + 10,
          //                 y: itemLayout[1],
          //                 style: {
          //                     fontSize: 12,
          //                     color: 'black',
          //                     text: data.getName(idx),
          //                     textAlign: 'left',
          //                     backgroundColor: '#000',
          //                     borderWidth: 1,
          //                     borderColor: '#ddd',
          //                     padding: 2,
          //                     cursor: 'pointer'
          //                 },
          //                 silent: true,
          //                 draggable: true
          //             }));
          //         }
          //     });
          // });

          window.addEventListener('resize', () => {
            myChart.resize();
          });
          state.loading = false;
          resolve(myChart);
        });
      });
    };

    // 点击切换重新渲染
    const reloadEchartsTree = (item) => {
      if (item.data.id) {
        initEchartsTree(item.data.id);
      }
    };

    // 选择用户
    const onSelectUser = () => {
      initEchartsTree(state.keyword ? state.keyword : state.userId);
    };
    // 重置
    const onReset = () => {
      state.keyword = '';
      initEchartsTree(state.userId);
    };
    const levelInit = (level) => {
      switch (level) {
        case 'NORMAL':
          return '普通用户';
          break;
        case 'V6':
          return '全球代理';
          break;
        case 'V5':
          return '全国代理';
          break;
        case 'V4':
          return '省代理';
          break;
        case 'V3':
          return '市代理';
          break;
        case 'V2':
          return '县代理';
          break;
        case 'V1':
          return '区代理';
        case 'V':
          return '代理';
          break;
      }
    };

    const handleQuery = () => {
      initEchartsTree(state.userId);
    };

    // 页面加载时
    onMounted(() => {
      // 阻止默认的右键菜单
      document.oncontextmenu = function (param) {
        return false;
      };
      let route = useRoute();
      console.log(route.query); //query传参
      state.userId = route.query.id ? route.query.id : null;
      initEchartsTree(state.userId).then((myChart) => {
        // 监听点击事件
        myChart.on('click', reloadEchartsTree);
        myChart.on('contextmenu', function (params) {
          // params 包含了当前点击节点的信息，例如 data 和 event
          console.log(params.data); // 打印节点数据
          console.log(params.event); // 打印原生事件对象
          ElMessageBox.prompt(`输入ID为${params.data.id}的分组序号`, '分组', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^[1-9]\d*$/,
            inputErrorMessage: '只能数字'
          })
            .then(({ value }) => {
              updateUser({
                userId: params.data.id,
                mark: value
              }).then((res) => {
                // 二次认证
                if (res.code == 200) {
                  if (res.msg == '0') {
                    // 二次验证弹框
                    state.twiceAuthCodeDialogVisible = true;
                  } else {
                    initEchartsTree(state.userId);
                  }
                }
              });
            })
            .catch(() => {
              // ElMessage({
              //   type: 'info',
              //   message: 'Input canceled',
              // })
            });
        });
      });
    });

    // 二次认证
    const twiceAuthSubmit = () => {
      openSafe({
        password: state.twiceAuthCode
      }).then((res) => {
        ElMessage.success('认证成功，2分钟内免输密码');
        state.twiceAuthCode = null;
        state.twiceAuthCodeDialogVisible = false;
      });
    };

    return {
      initTagViewHeight,
      onReset,
      changeId,
      //levelInit,
      handleQuery,
      twiceAuthSubmit,
      ...toRefs(state)
    };
  }
};
</script>

<style lang="scss" scoped>
.diagram-container {
  position: relative;
  padding: 20px;
}

.view-search {
  position: absolute;
  display: flex;
  right: 20px;
  top: 20px;
  z-index: 10;
  width: 550px;
}

.back-home {
  position: absolute;
  left: 20px;
  top: 10px;
  z-index: 10;
}
.auth-area1 {
  padding-left: 45px;
  padding-right: 45px;
  padding-top: 30px;
  padding-bottom: 30px;
}

.auth-tittle {
  font-size: 16px;
  margin-bottom: 16px;
}

.auth-code {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: center;
  align-items: center;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.auth-tips {
  margin-top: 16px;
  color: #777;
}

.auth-tips1 {
  margin-bottom: 16px;
  color: #a0cfff;
  font-size: 18px;
  text-align: center;
}

.auth-tips2 {
  margin-top: 26px;
  color: #79bbff;
  font-size: 12px;
  text-align: left;
}

.auth-tips-red {
  margin-top: 6px;
  color: #53a8ff;
}

.auth-input {
  width: 100%;
  margin-top: 26px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: center;
  align-items: center;
}

.auth-botton {
  width: 100%;
  margin-top: 26px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: center;
  align-items: center;
}
</style>
